<?php

namespace App\Utils;


use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;

class QueryUtil
{
    /**
     * @desc selectBuild
     * @param Builder $query
     * @param         $cond
     *    example: [
     *          ['var', '=']
     *      ]
     */
    public static function selectBuild(Builder $query, $data, $conds, $table='')
    {
        foreach($conds as $c){
            if(isset($data[$c[0]]) && ($data[$c[0]]??'null') !== 'null'){
                $column = $c[2] ?? $c[0];
                $ope = $c[1];
                $value = $data[$c[0]];
                if (!empty($table)){
                    $column = $table . '.' . $column;
                }
                if ($ope == 'in'){
                    $query->whereIn($column, $value);
                }elseif($ope == 'like') {
                    $query->where($c[0], 'like', "%{$value}%");
                }else{
                    if (strpos($c[0], '_before') !== false){
                        if(strlen($value) == 10) {
                            $value = date('Y-m-d', strtotime($value));
                            $value .= " 23:59:59";
                        }
                    }

                    if (strpos($c[0], '_after') !== false){
                        if(strlen($value) == 10) {
                            $value = date('Y-m-d', strtotime($value));
                            $value .= " 00:00:00";
                        }
                    }
                    $query->where($column, $ope, $value);
                }
            }
        }
    }

    public static function sortBuild(&$query, $data, $conds)
    {
        foreach ($conds as $k => $c) {
            if (!empty($data[$k])) {
                $direct =  $data[$k] == 1 ? 'asc' : 'desc';
                $query->orderBy($c, $direct);
            }
        }
    }

    public static function tableComment($tableName, $comment)
    {
        if($prefix = DB::getConfig('prefix')) {
            $tableName = $prefix . $tableName;
        }

        return DB::statement("ALTER TABLE `{$tableName}` comment '{$comment}'");
    }

    public static function queryList(Builder $query, $desc = 'id')
    {
        $page        = intval(request()->get('page', 1));
        $page_nation = intval(request()->get('pageSize', ResUtil::PAGENATION));
        $query->offset(($page - 1) * $page_nation);
        return $query->limit($page_nation)->orderByDesc($desc)->get();
    }

    public static function queryListParams(Builder $query, $desc = 'id')
    {
        $page        = intval(request()->get('page', 1));
        $page_nation = intval(request()->get('pageSize', ResUtil::PAGENATION));
        $query->offset(($page - 1) * $page_nation);
        return $query->limit($page_nation)->orderBy($desc, "ASC")->get();
    }

    public static function hasMore($size): int
    {
        return intval($size === intval(request()->get('pageSize', ResUtil::PAGENATION)));
    }
}
